import { defineStore } from 'pinia'

export const useCacheStore = defineStore('cache', {
  state: () => ({
    // 缓存的数据
    cachedData: {},
    // 缓存的页面组件
    cachedPages: new Set(),
    // 搜索历史
    searchHistory: JSON.parse(localStorage.getItem('searchHistory')) || [],
    // 浏览历史
    browseHistory: JSON.parse(localStorage.getItem('browseHistory')) || [],
  }),

  getters: {
    // 获取缓存数据
    getCachedData: (state) => (key) => {
      return state.cachedData[key]
    },

    // 检查页面是否被缓存
    isPageCached: (state) => (pageName) => {
      return state.cachedPages.has(pageName)
    },
  },

  actions: {
    // 设置缓存数据
    setCachedData(key, data, expireTime = 0) {
      this.cachedData[key] = {
        data,
        timestamp: Date.now(),
        expireTime,
      }
    },

    // 获取缓存数据（检查过期时间）
    getCachedDataWithExpiry(key) {
      const cached = this.cachedData[key]
      if (!cached) return null

      // 检查是否过期
      if (
        cached.expireTime > 0 &&
        Date.now() - cached.timestamp > cached.expireTime
      ) {
        delete this.cachedData[key]
        return null
      }

      return cached.data
    },

    // 清除指定缓存
    clearCachedData(key) {
      delete this.cachedData[key]
    },

    // 清除所有缓存
    clearAllCache() {
      this.cachedData = {}
      this.cachedPages.clear()
    },

    // 添加页面到缓存
    addCachedPage(pageName) {
      this.cachedPages.add(pageName)
    },

    // 移除页面缓存
    removeCachedPage(pageName) {
      this.cachedPages.delete(pageName)
    },

    // 添加搜索历史
    addSearchHistory(keyword) {
      if (!keyword.trim()) return

      // 移除已存在的相同关键词
      const index = this.searchHistory.indexOf(keyword)
      if (index > -1) {
        this.searchHistory.splice(index, 1)
      }

      // 添加到开头
      this.searchHistory.unshift(keyword)

      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10)
      }

      localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory))
    },

    // 清除搜索历史
    clearSearchHistory() {
      this.searchHistory = []
      localStorage.removeItem('searchHistory')
    },

    // 添加浏览历史
    addBrowseHistory(item) {
      // 移除已存在的相同项
      const index = this.browseHistory.findIndex((h) => h.id === item.id)
      if (index > -1) {
        this.browseHistory.splice(index, 1)
      }

      // 添加到开头
      this.browseHistory.unshift({
        ...item,
        timestamp: Date.now(),
      })

      // 限制历史记录数量
      if (this.browseHistory.length > 20) {
        this.browseHistory = this.browseHistory.slice(0, 20)
      }

      localStorage.setItem('browseHistory', JSON.stringify(this.browseHistory))
    },

    // 清除浏览历史
    clearBrowseHistory() {
      this.browseHistory = []
      localStorage.removeItem('browseHistory')
    },
  },
})
